package com.itlxd.controller;


import com.itlxd.common.ThreadLocalUtils;
import com.itlxd.entity.ShoppingCart;
import com.itlxd.entity.User;
import com.itlxd.exception.LoginException;
import com.itlxd.global.SysConstants;
import com.itlxd.global.SysMessages;
import com.itlxd.result.ResultVO;
import com.itlxd.service.IShoppingCartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 购物车 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2021-12-25
 */
@Api(tags = {"购物车相关接口"})
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private IShoppingCartService shoppingCartService;

    //查询购物车列表
    @ApiOperation("查询购物车列表接口")
    @GetMapping("/list")
    public ResultVO<List<ShoppingCart>> shoppingCartList(HttpSession session) {
        Object loginUser = session.getAttribute(SysConstants.LOGIN_USER);
        if (null == loginUser) {
            throw new LoginException(SysConstants.NO_LOGIN, SysMessages.NO_LOGIN);
        }
        List<ShoppingCart> shoppingCarts = shoppingCartService.listShoppingCarts(((User)loginUser).getId());

        return ResultVO.success(shoppingCarts, SysMessages.QUERY_SUCCESS);
    }

    //添加商品到购物车
    @ApiOperation("添加商品到购物车接口")
    @PostMapping("/add")
    public ResultVO<Integer> addShoppingCart(@RequestBody ShoppingCart shoppingCart) {
        Long currentId = ThreadLocalUtils.getCurrentId();
        shoppingCart.setUserId(currentId);
        Integer addNum = shoppingCartService.insertShoppingCart(shoppingCart);

        return ResultVO.success(addNum, SysMessages.INSERT_SUCCESS);
    }

    /**
     * 减少购物车中的商品
     * @param shoppingCart
     * @return
     */
    @PostMapping("/sub")
    public ResultVO<Integer> subShoppingCart(@RequestBody ShoppingCart shoppingCart) {
        shoppingCart.setUserId(ThreadLocalUtils.getCurrentId());
        int subNum = shoppingCartService.updateShoppingCart(shoppingCart);

        return ResultVO.success(subNum, SysMessages.UPDATE_SUCCESS);
    }

    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    public ResultVO<Integer> cleanShoppingCart() {
        Integer delNum = shoppingCartService.deleteShoppingCart(ThreadLocalUtils.getCurrentId());
        return ResultVO.success(delNum, SysMessages.DELETE_SUCCESS);
    }


}

